package com.lqg.bookLibrary.adminController;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lqg.bookLibrary.common.constant.HostParam;
import com.lqg.bookLibrary.common.core.domain.JsonResult;
import com.lqg.bookLibrary.pojo.Books;
import com.lqg.bookLibrary.pojo.Users;
import com.lqg.bookLibrary.service.IBooksService;
import com.lqg.bookLibrary.service.IUsersService;
import com.lqg.bookLibrary.service.webService.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/manage/book")
@PreAuthorize("hasAnyRole('a')")
public class ManageBookController {

    @Autowired
    private IBooksService booksService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private FileService fileService;

    @GetMapping("/read/{pageNum}")
    //@PreAuthorize("@ex.hasAuthority('system:dept:list')")
    public JsonResult read(@PathVariable int pageNum) {
        long count = booksService.count();
        int maxCun = 20;
        int chu = (pageNum-1)*maxCun;
        List<Books> list = booksService.lambdaQuery()
                .last("limit " + chu + "," + maxCun)
                .list();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", list);
        jsonObject.put("pages", (int)(count/maxCun)+1);
        jsonObject.put("nowPage", pageNum);

        return JsonResult.success(jsonObject);
    }


    @PostMapping("/update")
    public JsonResult update(@RequestBody String post){
        Books books = JSON.parseObject(post, Books.class);
        books.setUpdatedAt(null);
        books.setCreatedAt(null);
        booksService.updateById(books);
        Books one1 = booksService.lambdaQuery().eq(Books::getBookId, books.getBookId()).one();
        return JsonResult.success(one1);
    }


    @GetMapping("/delete/{id}")
    public JsonResult delete(@PathVariable Long id){
        boolean b = booksService.removeById(id);
        if (b) {
            return JsonResult.success();
        }else {
            return JsonResult.fail("删除失败");
        }
    }


    @PostMapping("/insert")
    public JsonResult insert(@RequestBody String post){
        Books books = JSON.parseObject(post, Books.class);
        booksService.save(books);
        Books one = booksService.lambdaQuery()
                .eq(Books::getTitle, books.getTitle())
                .eq(Books::getAuthor,books.getAuthor())
                .eq(Books::getPublisher,books.getPublisher())
                .one();
        return JsonResult.success(one);
    }

    @PostMapping("/avatar/upload")
    public JsonResult uploadAvatar(@RequestParam("avatar") MultipartFile zipFile,
                                   @RequestParam Long id){
        // 文件保存
        String filePath = HostParam.MAIN_PATH + "/book/";
        String fileName = id +"_pic.jpg";
        String fwUri = HostParam.ACCESS_PATH + "/book/" +fileName;
        fileService.upLoadFile(zipFile, filePath, fileName);
        return JsonResult.success("success",fwUri);
    }

    @PostMapping("/search")
    public JsonResult search(@RequestBody String post){
        JSONObject jsonObject = JSONObject.parseObject(post);
        String condition = jsonObject.get("condition").toString();
        String content = jsonObject.get("content").toString();
        //System.out.printf(condition + "     " + content);

        condition = StrUtil.toUnderlineCase(condition);

        QueryWrapper<Books> wrapper = new QueryWrapper<>();
        wrapper.eq(condition, content);
        List<Books> list = booksService.list(wrapper);

        JSONObject result = new JSONObject();
        result.put("data", list);
        result.put("pages", 1);
        result.put("nowPage", 1);

        return JsonResult.success(result);
    }


}
